<template>
  <div class="header-row">
  <div style="font-size: 20px;">新增科室</div>
    <div style="display: flex; gap: 10px; margin-left: auto;">
      <el-button type="primary" class="export-btn" @click="handleExport" style="">导出</el-button>
      <el-button type="danger" class="batch-delete-btn" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除</el-button>
      <el-button type="primary" class="add-btn" @click="dialogVisible = true" style="">新增科室</el-button>
    </div>
  </div>
      <el-cascader style="margin-top: 20px;"
        v-model="departmentName"
        :options="departmentOptions"
        placeholder="请选择科室"
        clearable
        class="cascader-select"
        :props="cascaderProps"
        :loading="loading"
      />
      <el-button type="primary" class="search-btn" @click="onSearch" style="margin-top: 20px; margin-left: 20px;" >查询</el-button>
  <div>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      style="width: 100%; margin-top: 24px;"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="departmentName" label="科室名称" />
      <el-table-column prop="campusName" label="院区名称" />
      <el-table-column
        prop="paretId"
        label="父级科室"
        :formatter="(row: any) => departmentIdNameMap[row.paretId] || row.paretId || '-'"
      />
      
      <!-- <el-table-column prop="campusId" label="院区ID" /> -->
      <el-table-column prop="departmentAddr" label="科室地址" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" type="primary" @click="onEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="text" @click="onDeleteConfirm(scope.row)" class="delete-icon-btn">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect x="5" y="8" width="14" height="11" rx="2" fill="#1677ff"/>
              <rect x="9" y="11" width="2" height="6" rx="1" fill="white"/>
              <rect x="13" y="11" width="2" height="6" rx="1" fill="white"/>
              <rect x="3" y="6" width="18" height="2" rx="1" fill="#1677ff"/>
              <rect x="8" y="3" width="8" height="2" rx="1" fill="#1677ff"/>
            </svg>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total, first, last"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :hide-on-single-page="false"
        :pager-count="5"
        :page-sizes="[10, 20, 50, 100]"
        style="margin-top: 16px;"
      />
    </div>
    <el-dialog v-model="dialogVisible" title="新增科室信息" width="500px">
      <el-form :model="addForm" label-width="100px" :rules="addRules" ref="addFormRef">
        <el-form-item label="科室名称" prop="departmentName">
          <el-input v-model="addForm.departmentName" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="院区" prop="campusId">
          <el-select v-model="addForm.campusId" placeholder="请选择院区">
            <el-option v-for="item in campusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="父级科室" prop="paretId">
          <el-cascader
            v-model="addForm.paretIdArr"
            :options="departmentOptions"
            :props="{ value: 'id', label: 'departmentName', children: 'children', checkStrictly: true }"
            clearable
            placeholder="请选择父级科室"
          />
        </el-form-item>
        <el-form-item label="科室地址" prop="departmentAddr">
          <el-input v-model="addForm.departmentAddr" placeholder="请输入科室地址" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="addForm.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddDepartment">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { axiosrmedical } from '@/http/axiosRead'
import { axioswmedical } from '@/http/axiosWrtie'

const departmentName = ref<string[]>([])
const departmentOptions = ref<any[]>([])
const loading = ref(false)

// 新增科室弹窗
const dialogVisible = ref(false)
const addFormRef = ref()
const addForm = ref({
  departmentName: '',
  campusId: '',
  paretIdArr: [],
  departmentAddr: '',
  status: true
})
const addRules = {
  departmentName: [{ required: true, message: '请输入科室名称', trigger: 'blur' }],
  campusId: [{ required: true, message: '请选择院区', trigger: 'change' }],
  paretIdArr: [{ required: true, message: '请选择父级科室', trigger: 'change' }],
  departmentAddr: [{ required: true, message: '请输入科室地址', trigger: 'blur' }]
}
const campusOptions = ref<any[]>([])

// 表格相关
const tableData = ref<any[]>([])
const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// Element Plus Cascader props
const cascaderProps = {
  value: 'departmentName',
  label: 'departmentName',
  children: 'children',
  checkStrictly: true, // 可选任意一级
}

// 递归转换children为对象数组
function normalizeDepartments(arr: any[]): any[] {
  return arr.map(item => {
    let children = []
    if (Array.isArray(item.children) && item.children.length > 0 && typeof item.children[0] === 'string') {
      children = item.children.map((name: string, idx: number) => ({
        id: `${item.id}-${idx}`,
        departmentName: name,
        children: []
      }))
    } else if (Array.isArray(item.children)) {
      children = normalizeDepartments(item.children)
    }
    return {
      ...item,
      id: item.id, // 保证有id字段
      departmentName: item.departmentName,
      children: children.length ? children : undefined
    }
  })
}

// 获取科室树数据
const fetchDepartmentTree = async () => {
  loading.value = true
  try {
    const res = await axiosrmedical.get('/Department/DepartmentTree')
    departmentOptions.value = normalizeDepartments(res.data.data || [])
  } catch (e) {
    departmentOptions.value = []
  } finally {
    loading.value = false
  }
}

// 获取表格数据
const fetchDepartmentTable = async () => {
  tableLoading.value = true
  try {
    const res = await axiosrmedical.get('/Department/Handle', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        departmentName: Array.isArray(departmentName.value) && departmentName.value.length
          ? departmentName.value[departmentName.value.length - 1]
          : undefined
      }
    })
    tableData.value = res.data.pageData || []
    total.value = res.data.total || 0
  } catch (e) {
    tableData.value = []
    total.value = 0
    ElMessage.error('获取科室表格数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 获取院区下拉数据
const fetchCampusOptions = async () => {
  try {
    const res = await axiosrmedical.get('/Campus/GetCampus')
    // 假设后端返回数组，每项有 id 和 campusName 字段
    campusOptions.value = (res.data.data || []).map((item: any) => ({
      value: item.id,
      label: item.campusName
    }))
  } catch (e) {
    campusOptions.value = []
  }
}

const handleAddDepartment = async () => {
  await addFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    try {
      await axios.post('http://localhost:5289/Department/AddDepartment', {
        departmentName: addForm.value.departmentName,
        campusId: addForm.value.campusId,
        paretId: addForm.value.paretIdArr.length ? addForm.value.paretIdArr[addForm.value.paretIdArr.length - 1] : 0,
        departmentAddr: addForm.value.departmentAddr,
        status: addForm.value.status
      })
      ElMessage.success('新增科室成功')
      dialogVisible.value = false
      addForm.value = { departmentName: '', campusId: '', paretIdArr: [], departmentAddr: '', status: true }
      fetchDepartmentTable()
      fetchDepartmentTree()
    } catch (e) {
      ElMessage.error('新增科室失败')
    }
  })
}

// 导出Excel
const handleExport = async () => {
  try {
    const response = await axios({
      url: 'http://localhost:5042/Department/ExportExcel/ExportExcel',
      method: 'GET',
      responseType: 'blob',
    })
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '科室信息.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (e) {
    ElMessage.error('导出失败')
  }
}

// 批量删除
const multipleSelection = ref<any[]>([])

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

const handleBatchDelete = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请先选择要删除的科室')
    return
  }
  ElMessageBox.confirm(
    `确定要批量删除选中的${multipleSelection.value.length}个科室吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const ids = multipleSelection.value.map(item => item.id)
      await axios.post('http://localhost:5289/Department/PLDeleteDepartment', { ids, status: true })
      ElMessage.success('批量删除成功')
      fetchDepartmentTable()
      fetchDepartmentTree()
      multipleSelection.value = []
    } catch (e) {
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {
    // 取消删除，无需处理
  })
}

// 弹窗打开时加载院区数据
watch(dialogVisible, (val) => {
  if (val) fetchCampusOptions()
})

onMounted(() => {
  fetchDepartmentTree()
  fetchDepartmentTable()
})

watch([pageNum, pageSize], () => {
  fetchDepartmentTable()
})

const handlePageChange = (val: number) => {
  pageNum.value = val
}
const handleSizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
}
const onSearch = () => {
  pageNum.value = 1
  fetchDepartmentTable()
}

// 操作列按钮事件（暂未实现具体功能）
const onEdit = (row: any) => {
  ElMessage.info('编辑功能待实现: ' + row.departmentName)
}

const onDeleteConfirm = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.post('http://localhost:5289/Department/DeleteDepartment', {
        id: row.id
      })
      ElMessage.success('删除成功')
      fetchDepartmentTable()
      fetchDepartmentTree()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除，无需处理
  })
}

const departmentIdNameMap = computed(() => {
  const map: Record<string | number, string> = {}
  function traverse(list: any[]) {
    list.forEach(item => {
      map[item.id] = item.departmentName
      if (item.children && item.children.length) {
        traverse(item.children)
      }
    })
  }
  traverse(departmentOptions.value)
  return map
})
</script>

<style scoped>
.department-page {
  max-width: 900px;
  margin: 40px auto;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.add-btn {
  min-width: 100px;
}
.cascader-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}
.cascader-select {
  flex: 1;
}
.search-btn {
  min-width: 80px;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>

